//
//  HomeChatViewController.swift
//  NDAi
//
//  Created by 丸子 on 2024/7/17.
//

import UIKit
import IQKeyboardManagerSwift

class HomeChatViewController: BaseViewController {
    var viewModel = HomeViewModel()
    let disposeBag = DisposeBag()
    var model:PlazaListModel?
    private lazy var tableView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .plain)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.rowHeight = UITableView.automaticDimension
        tableView.register(cellWithClass: HomeMessageCell.self)
        tableView.separatorStyle = .none
        tableView.backgroundColor = .clear
        tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 64, right: 0)
        return tableView
    }()
    lazy var inputViwe: HomeInputVIew = {
        let view = HomeInputVIew()
        return view
    }()
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        IQKeyboardManager.shared.keyboardDistanceFromTextField = -bottomSafeAreaHeight
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        viewModel.stopTimer()
        IQKeyboardManager.shared.keyboardDistanceFromTextField = -(kMusicBarHeight - 13)
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor(hexString: "#F3F2F7")
        self.navigationItem.title = "你的AI"
        self.view.addSubview(tableView)
        self.view.addSubview(inputViwe)
        tableView.snp.makeConstraints { make in
            make.top.equalTo(self.safeTop)
            make.leading.trailing.equalToSuperview()
            make.bottom.equalTo(inputViwe.snp.top)
        }
        inputViwe.snp.makeConstraints { make in
            make.bottom.equalToSuperview()
            make.leading.trailing.equalToSuperview()
            make.height.equalTo(56 + bottomSafeAreaHeight)
        }
        inputViwe.sendBtn.setClosureTouchUpInside_k { [weak self] in
            self?.sendMessage()
        }
        bindEvent()
        viewModel.loadData()
        if let model = model {
            self.viewModel.addQa(question: model.item?.first?.question ?? "", answer: model.item?.first?.answer ?? "")
        }
        
        initUI()
    }
    
    func initUI(){
        let rightBtn = UIButton(type: .custom)
        rightBtn.setImage(UIImage(named: "icon_home_sub"), for: .normal)
        rightBtn.backgroundColor = UIColor(hexString: "#464957")
        rightBtn.setTitle("订阅", for: .normal)
        rightBtn.allRound(12)
        rightBtn.titleLabel?.font = UIFont.pingFangSCRegular(ofSize: 15)
        rightBtn.layoutButtonWithEdgeInsetsStyle(.Left, space: 5)
        rightBtn.contentEdgeInsets = UIEdgeInsets(top: 2, left: 12, bottom: 3, right: 12)
        let rightItem = UIBarButtonItem(customView: rightBtn)
        self.navigationItem.rightBarButtonItem = rightItem
        
        rightBtn.setClosureTouchUpInside_k { [weak self] in
            if Appearance.shared.accoutModel != nil {
                let vc = SubscribeViewController()
                self?.navigationController?.pushViewController(vc, animated: true)
            }else {
                GlobalRx.loginSubject.onNext(())
            }
        }
    }
    
    
    func bindEvent(){
        self.viewModel.messageEventSubject.subscribe(onNext: { [weak self] code, msg in
            guard let self = self else { return }
            DispatchQueue.main.async {
                self.tableView.reloadData()
                if code == 1 { //滚动到底部
                    self.scrollToBottom()
                }else if code == -1 {//隐藏键盘
                    kHideKeyboard()
                }
                if let msg = msg {
                    NDProgressHUD.show(message: msg)
                }
            }
        }).disposed(by: disposeBag)
        
        viewModel.reloadDataSubject.subscribe { _ in
            self.tableView.reloadData()
        }.disposed(by: disposeBag)
        
        viewModel.messageStateSubject.subscribe(onNext: { [weak self] in
            guard let self = self else { return }
            self.inputViwe.sendBtn.isSelected = self.viewModel.isGenerated
        }).disposed(by: disposeBag)
    }
    func sendMessage(){
        if let text = inputViwe.inputFiled.text, text.count > 0 {
            self.inputViwe.inputFiled.text = ""
            kHideKeyboard()
            self.viewModel.checkWords(message: text)
        }else {
            NDProgressHUD.showSuccess(title: "", subtitle: "请输入你想问的问题!")
        }
    }
    func openMenuWithMessage(model:AIMessage, point:CGPoint, index:Int) {
        let vc = AIMenuViewController()
        vc.position = point
        //        vc.transitioningDelegate = /*customTransitioningDelegate*/
        vc.modalPresentationStyle = .custom
        self.present(vc, animated: false)
        
        vc.chooseType = { [weak self] type in
            self?.processingLongPress(type: type, model: model)
        }
    }
    
    func processingLongPress(type:Int, model:AIMessage) {
        if type == 1 {
            UIPasteboard.general.string = model.message ?? ""
            NDProgressHUD.show(message: "复制成功")
        }else if type == 2 {
            SqlManager.shared.delete(from: AIMessage.self, where: AIMessage.Properties.sort == model.sort ?? 0)
            NDProgressHUD.show(message: "删除成功")
        }else if type == 3 {
            var model = model
            model.collect = true
            SqlManager.shared.update(on: [AIMessage.Properties.collect], with: model, where: AIMessage.Properties.sort == model.sort ?? 0)
            NDProgressHUD.show(message: "收藏成功")
        }
    }
}

extension HomeChatViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.viewModel.messageList.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let model = self.viewModel.messageList[indexPath.item]
        let cell = tableView.dequeueReusableCell(withClass: HomeMessageCell.self)
        cell.setup(message: model)
        cell.chooseLongPress = { [weak self] in
            guard let self = self else { return }
            kHideKeyboard()
            UIView.animate(withDuration: 0.3, animations: {
                // 动画部分可以为空
            }) { [weak self, weak cell] finished in
                guard let self = self, let cell = cell else { return }
                let rect = self.tableView.convert(cell.frame, to: self.view)
                let point = CGPoint(x: cell.contentV.x, y: rect.origin.y)
                self.openMenuWithMessage(model: model, point: point, index: indexPath.item)
            }
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        section == 0 ? 0.01 : 0.01
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func scrollToBottom() {
        tableView.reloadData()
        let numberOfSections = tableView.numberOfSections
        let numberOfRows = tableView.numberOfRows(inSection: numberOfSections - 1)
        if numberOfRows > 0 {
            let indexPath = IndexPath(row: numberOfRows - 1, section: numberOfSections - 1)
            tableView.scrollToRow(at: indexPath, at: .bottom, animated: true)
        }
    }
    
}
